package com.jiangge.caiji.uoso;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jiangge.caiji.utils.WebResource;

public class UosoUtils {

	/**
	 * @param sstr
	 * @param reg
	 * @return
	 */
	public static List<String> getStringList(String sstr,String reg) {
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(sstr);
		List<String> list = new ArrayList<String>();
		while(matcher.find()) {
			String destr = matcher.group();
			list.add(destr);
		}
		return list;
	}
	
	/**
	 * @param sstr
	 * @param reg
	 * @return
	 */
	public static String getString(String sstr,String reg) {
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(sstr);
		String str = null;
		while(matcher.find()) {
			str = matcher.group();
		}
		return str;
	}

	public static void main(String args[]) {
		List<String> newlist = getActicle();
		for(String s:newlist){
			System.out.println(s);
		}
	}
	
	public static List<String> getActicle(){
		String sstr = getHtml(WebResource.getUrl("kongfu"));
		String reg = "<td class=\"l\"><a href=\"(.+?)\" target=\"_blank\" >(.+?)</a></td>";
		List<String> oldlist = getStringList(sstr,reg);
		List<String> newlist = new ArrayList<String>();
		String urlreg = "\\/\\?s=(.+?).html";
		for (String s:oldlist) {
			String sr = "http://hao.uoso.net"+getString(s,urlreg);
			newlist.add(sr);
		}
		return newlist;
	}
	
	public static String getHtml(String url){
		StringBuffer strLine = new StringBuffer();
		try {
			URL urlObj = new URL(url);
			InputStream streamObj = urlObj.openStream();
			InputStreamReader readerObj = new InputStreamReader(streamObj);
			BufferedReader buffObj = new BufferedReader(readerObj);
			while ((buffObj.readLine()) != null) {
				strLine.append(buffObj.readLine());
			}
			buffObj.close();
		} catch (Exception e) {
			System.err.println("url error");
		}
		return strLine.toString();
	}
}
